package com.summer.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.summer.edu.entity.Subject;
import com.summer.edu.entity.excel.SubjectData;
import com.summer.edu.entity.subject.OneSubject;
import com.summer.edu.entity.subject.TwoSubject;
import com.summer.edu.listener.SubjectExcelListener;
import com.summer.edu.mapper.SubjectMapper;
import com.summer.edu.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-01-11
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    @Override
    public void saveSubject(MultipartFile file,SubjectService subjectService) {
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, SubjectData.class,new SubjectExcelListener(subjectService)).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        QueryWrapper<Subject> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id","0");
        List<Subject> oneSubjectList = baseMapper.selectList(wrapperOne);

        QueryWrapper<Subject> wrapperTwo = new QueryWrapper<>();
        wrapperTwo.ne("parent_id","0");
        List<Subject> twoSubjectList = baseMapper.selectList(wrapperTwo);

        List<OneSubject> finalSubjectList =new ArrayList<>();
        for (int i = 0; i <oneSubjectList.size() ; i++) {
            Subject subject = oneSubjectList.get(i);
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(subject,oneSubject);
            finalSubjectList.add(oneSubject);
            List<TwoSubject> twoSubjectFinalList = new ArrayList<>();
            for (int j = 0; j <twoSubjectList.size() ; j++) {
                Subject twoSubject = twoSubjectList.get(j);
                if (twoSubject.getParentId().equals(subject.getId())){
                    TwoSubject twoSubject1 = new TwoSubject();
                    BeanUtils.copyProperties(twoSubject,twoSubject1);
                    twoSubjectFinalList.add(twoSubject1);
                }
            }
            oneSubject.setChildren(twoSubjectFinalList);
        }

        return finalSubjectList;
    }
}
